package io

import (
	"bufio"
	"bytes"
	"fmt"
	"io"
	"io/ioutil"
	"os"
)

func FileRead() {
	file, err := os.Open("/Users/fanshuai/keywords.txt")
	if err != nil {
		fmt.Println("open file error, " + err.Error())
		return
	}

	defer file.Close()

	buf := new(bytes.Buffer)
	var data [128]byte
	for {
		n, err := file.Read(data[:])
		if err == io.EOF {
			fmt.Println("文件读完了")
			break
		}
		if err != nil {
			fmt.Println("err=" + err.Error())
			return
		}
		if n == 0 {
			break
		}

		buf.Write(data[:n])
	}

	fmt.Println(buf.String())
}

func FileRead2() {
	file, err := os.OpenFile("/Users/fanshuai/keywords.txt", os.O_RDONLY, 0666)
	if err != nil {
		fmt.Println("err =" + err.Error())
		return
	}

	defer file.Close()
	bufReader := bufio.NewReader(file)

	var arr []string
	for {
		line, err := bufReader.ReadString('\n')
		if err == io.EOF {
			break
		}
		if err != nil {
			fmt.Println("err=" + err.Error())
			return
		}

		arr = append(arr, line)
	}

	fmt.Println(arr)
}

func FileRead3() {
	file, err := os.OpenFile("/Users/fanshuai/keywords.txt", os.O_RDONLY, 0666)
	if err != nil {
		fmt.Println("err=" + err.Error())
		return
	}

	defer file.Close()

	data, err := ioutil.ReadAll(file)
	if err != nil {
		fmt.Println("err=" + err.Error())
		return
	}
	fmt.Println(string(data))
}

func FileWrite1() {
	file, err := os.OpenFile("/Users/fanshuai/1.txt", os.O_CREATE|os.O_WRONLY|os.O_TRUNC, 0666)
	if err != nil {
		fmt.Println("err = " + err.Error())
		return
	}

	defer file.Close()

	msg := "hello world\n"
	file.Write([]byte(msg))
	file.WriteString(msg)
}

func FileWrite2() {
	file, err := os.OpenFile("/Users/fanshuai/2.txt", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
	if err != nil {
		fmt.Println("err = " + err.Error())
		return
	}

	defer file.Close()
	bufWriter := bufio.NewWriter(file)
	for i := 0; i < 10; i++ {
		bufWriter.WriteString("hello world\n")
	}

	bufWriter.Flush()
}

func FileWrite3() {
	ioutil.WriteFile("/Users/fanshuai/3.txt", []byte("aaa"), 0666)
}

// CopyFile 拷贝文件函数
func CopyFile(dstName, srcName string) (written int64, err error) {
	// 以读方式打开源文件
	src, err := os.Open(srcName)
	if err != nil {
		fmt.Printf("open %s failed, err:%v.\n", srcName, err)
		return
	}
	defer src.Close()
	// 以写|创建的方式打开目标文件
	dst, err := os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE, 0644)
	if err != nil {
		fmt.Printf("open %s failed, err:%v.\n", dstName, err)
		return
	}
	defer dst.Close()
	return io.Copy(dst, src) //调用io.Copy()拷贝内容
}

func TestIO() {
	CopyFile("/Users/fanshuai/3.txt", "/Users/fanshuai/keywords.txt")
}
